#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import logging, datetime
import time
import threading


class XLogger(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        time.sleep(1)

        logging.basicConfig(filename='logger.log', format='%(asctime)s - %(levelname)s - %(message)s',
                            level=logging.INFO)
        self.logger = logging.getLogger(__name__)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        filehandler = logging.FileHandler("log_%s.txt" % (datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')))
        filehandler.setLevel(logging.INFO)
        filehandler.setFormatter(formatter)

        consoleHandler = logging.StreamHandler()  # 日志信息显示在终端terminal
        consoleHandler.setLevel(logging.INFO)
        consoleHandler.setFormatter(formatter)

        self.logger.addHandler(filehandler)
        self.logger.addHandler(consoleHandler)
        pass

    @classmethod
    def instance(cls, *args, **kwargs):
        with XLogger._instance_lock:
            if not hasattr(XLogger, "_instance"):
                XLogger._instance = XLogger(*args, **kwargs)
        return XLogger._instance
